import { hsqj_input_common_GSDGB } from './hsqj-input-common.js';

/**
 * 等待/延迟处理
 * @param {number} timeout 延迟时间 单位毫秒，默认1秒
 */
export function delay(timeout = 1000) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, timeout);
  });
}

/**
 * post message
 * @param {string} event 事件名
 * @param {object} data 数据
 * @param {string} url 默认 *
 */
export function postMsg(event, data, url = '*') {
  const msg = { event, data };

  console.group(`发送事件 - ${event}`);
  console.dir(msg);
  console.groupEnd();

  window.postMessage(JSON.stringify(msg), url);
}

/**
 * 目标对象是否是object类型
 * @param {any} target 目标对象
 */
export function isObject(target) {
  return Object.prototype.toString.call(target) === '[object Object]';
}

function getQuery(params, keys) {
  let value;

  for (let i = 0; i < keys.length; i += 1) {
    const key = keys[i];
    value = params.get(key);
    if (value) {
      break;
    }
  }

  return value;
}

/**
 * 由URL中获取期间的开始、结束时间 yyyy-MM
 * @param {Array<string>} startKeys 开始时间 ["skssq_q", "skssqQ"]
 * @param {Array<string>} endKeys 结束时间 ["skssq_z", "skssqZ"]
 */
export function getPeriodFromURL(
  startKeys = ['skssq_q', 'skssqQ'],
  endKeys = ['skssq_z', 'skssqZ']
) {
  const url = new URL(window.location.href);
  let startTime = getQuery(url.searchParams, startKeys);
  startTime = startTime ? startTime.slice(0, 7) : '';
  let endTime = getQuery(url.searchParams, endKeys);
  endTime = endTime ? endTime.slice(0, 7) : '';

  return [startTime, endTime];
}

/**
 * 发送数据查询条件
 * @param {string} type 税种类型，默认 balance，可用类型 zzs:增值税,sds:所得税,balance:资产负债表,profit:利润表,cash:现金流量表
 */
export function postFilters(type = 'balance', sbqq, sbqz) {
  let startTime;
  let endTime;
  if (!sbqq || !sbqz) {
    const arr = getPeriodFromURL();
    startTime = arr[0];
    endTime = arr[1];
  } else {
    startTime = sbqq && sbqq.length > 7 ? sbqq.slice(0, 7) : '';
    endTime = sbqz && sbqz.length > 7 ? sbqz.slice(0, 7) : '';
  }

  console.dir(startTime, endTime);

  postMsg('setPeriodAndType', { type, startTime, endTime });
}

export function postNationData(baseInfo, taxType) {
  if (!baseInfo) {
    console.error('基础信息为空');
    return;
  }

  // institutionCode 取值 1是企业会计准则，2是小企业会计准则
  const institution = baseInfo.companyInfo.institutionCode === '2';

  const isCwbb = ['balance', 'profit', 'cash'].includes(taxType);
  let saasInstitution = '';
  const isDalian = baseInfo.companyInfo.cityId === 210200;
  if (isCwbb) {
    const clientNameSelector = isDalian
      ? '.layui-layer-iframe .layui-layer-title'
      : '#sbbName';
    const clientName = document.querySelector(clientNameSelector).innerText;
    const keywords = isDalian
      ? ['财务报表', '小企业', '企业']
      : ['会计准则', '小企业会计准则', '未执行新准则的一般企业'];

    if (!clientName.includes(keywords[0])) {
      throw new Error('不支持的财务报表');
    }

    if (clientName.includes(keywords[1])) {
      saasInstitution = 2;
    } else if (clientName.includes(keywords[2])) {
      saasInstitution = 1;
    }
  } else if(isDalian) {

  }

  const taxInfo = {
    institution: institution ? '2013' : '2007', // 国税对应制度 2007 | 2013
    nsrsbh: '', // 纳税人申报号
    nsrmc: '', // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '', // 税款所属期止
    isZip: false, // 是否压缩包
    saasInstitution,
  };

  if (taxType === 'hsqj') {
    taxInfo.isHsqjSmall = institution;
  }

  postMsg('backNationData', { taxInfo });
}

export async function fillTable(baseInfo, sheetData) {
  const { saasData } = sheetData;
  const { sheet } = saasData;

  switch (sheet) {
    case 'hsqj-gener':
    case 'hsqj-small': {
      await hsqj_input_common_GSDGB(sheetData, baseInfo);
      break;
    }

    case 'balance':
    case 'cash':
    case 'profit': {
      await hsqj_input_common_GSDGB(sheetData, baseInfo);
      break;
    }

    default:
      break;
  }
}

/**
 * 消息处理配置
 * @typedef {Object} MessageOption
 * @property {Object} baseInfo - 基础信息
 * @property {RegExp} loginURLExp - 登录页面URL正则， 默认为 /\/sso\/login/g
 * @property {Function} onBaseInfo - getBaseInfo 消息处理函数
 * @property {Function} onNationData - getNationData 消息处理函数
 * @property {Function} onSaasData - setSaasData 消息处理函数
 */

function defaultNationDataHandler(baseInfo, data) {
  postNationData(baseInfo, data.data.taxType);
}

/**
 * 默认onSaasData处理函数
 */
async function defaultSaasDataHandler(baseInfo, data) {
  let sheetData = data;
  await fillTable(baseInfo, sheetData);
}

/**
 * 简单消息处理函数
 * @param {Message} msg 消息对象
 * @param {MessageOption} options  消息处理配置
 */
export function buildMsgHandler(options) {
  let { baseInfo } = options;
  const {
    loginURLExp = /\/sso\/login/g,
    onBaseInfo,
    onNationData = defaultNationDataHandler,
    onSaasData = defaultSaasDataHandler,
  } = options;

  return async ({ data }) => {
    if (typeof data === 'string') {
      data = JSON.parse(data);
    }

    // 只监听来自于content script的信息
    if (data.sender !== 'content-script') {
      return false;
    }

    console.group(`接收事件 - ${data.event}`);
    console.dir(data);
    console.groupEnd();

    switch (data.event) {
      // 获得基本信息
      case 'getBaseInfo': {
        baseInfo = data.data;

        // 当前为登录页
        if (
          loginURLExp &&
          loginURLExp.test(window.location.href) &&
          onBaseInfo
        ) {
          await onBaseInfo(baseInfo);
        }
        break;
      }

      // 根据页面信息修改请求信息
      case 'getNationData': {
        onNationData(baseInfo, data);
        break;
      }

      // 点击一键报税后获得的信息
      case 'setSaasData': {
        onSaasData(baseInfo, data.data);
        break;
      }
      default:
        break;
    }
  };
}

export function updateNgModel(updater) {
  const frmSheet = window.frames.frmMain.frames.frmSheet;
  const scope = frmSheet.angular
    .element(frmSheet.document.querySelector('.NewTableMain'))
    .scope();

  scope.$apply(() => {
    updater(scope);
  });
}

export function fireEvent(el, type) {
  let e;
  if (window.Event) {
    e = new window.Event(type, { bubbles: true, cancelable: true });
  } else {
    e = document.createEvent('HTMLEvents');
    e.initEvent(type, true, true);
  }
  el.dispatchEvent(e);
}

export function changeInputValue(ele, val) {
  ele.value = val;
  var event = document.createEvent('HTMLEvents');
  event.initEvent("input", true, true);
  event.eventType = 'message';
  ele.dispatchEvent(event);
}

export async function tpassLogin(baseInfo) {
  await delay(500);
  const { nationalTaxId, nationalTaxAccount, nationalTaxPass } =
    baseInfo.companyInfo || {};
  if (!nationalTaxId || !nationalTaxAccount || !nationalTaxPass) {
    console.warn('税局登录信息不完整');
  }
  const form = document.getElementsByTagName('form')[0];
  changeInputValue(form[0], nationalTaxId);
  changeInputValue(form[1], nationalTaxAccount);
  changeInputValue(form[2], nationalTaxPass);
}

// async function loginStop(onBaseInfo, baseInfo) {
//   if (window.location.pathname === '/xxmh/') {
//     await delay(1000)
//     document.getElementById('kxText').click()
//   }

//   if (/\/sso\/login/g.test(window.location.pathname)) {
//     await delay(1000)
//     document.getElementById('mmdl_QieHuan').click();
//     onBaseInfo(baseInfo)
//   }
// }
